const getWsUrl = () => {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const hostname = window.location.hostname || 'localhost'
  const port = process.env.NODE_ENV === 'development' ? ':8888' : ''
  return `${protocol}//${hostname}${port}/ws`
}

class WebSocketClient {
  constructor() {
    this.ws = null
    this.subscriptions = new Map()
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectTimeout = 3000
    this.isConnecting = false
    this.heartbeatInterval = null
    this.heartbeatTimeout = null
    this.connectionError = false
  }

  connect() {
    if (this.isConnecting) return
    if (this.connectionError) return // 如果已经确认有连接错误，不再尝试

    this.isConnecting = true
    const wsUrl = getWsUrl()
    
    try {
      console.log(`尝试连接WebSocket: ${wsUrl}`)
      this.ws = new WebSocket(wsUrl)
      this.ws.onopen = this.onConnected.bind(this)
      this.ws.onclose = this.onDisconnected.bind(this)
      this.ws.onerror = this.onError.bind(this)
      this.ws.onmessage = this.onMessage.bind(this)
      
      // 设置超时
      setTimeout(() => {
        if (this.ws && this.ws.readyState !== WebSocket.OPEN) {
          console.warn('WebSocket连接超时')
          this.connectionError = true
          if (this.ws) {
            this.ws.close()
          }
        }
      }, 5000) // 5秒连接超时
    } catch (error) {
      console.error('WebSocket连接错误:', error)
      this.connectionError = true
      this.isConnecting = false
    }
  }

  onConnected() {
    console.log('WebSocket连接成功')
    this.isConnecting = false
    this.reconnectAttempts = 0
    this.connectionError = false
    this.startHeartbeat()
  }

  onDisconnected() {
    console.log('WebSocket断开连接')
    this.isConnecting = false
    this.clearHeartbeat()

    if (!this.connectionError) {
      this.handleReconnect()
    }
  }

  onError(error) {
    console.error('WebSocket错误:', error)
    this.connectionError = true
    this.isConnecting = false
  }

  onMessage(event) {
    try {
      const data = JSON.parse(event.data)
      if (data.type === 'pong') {
        // 心跳响应
        clearTimeout(this.heartbeatTimeout)
        return
      }

      const topic = data.topic
      const callback = this.subscriptions.get(topic)
      if (callback) {
        callback(data.payload)
      }
    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
    }
  }

  startHeartbeat() {
    this.clearHeartbeat()
    if (!this.connectionError) {
      this.heartbeatInterval = setInterval(() => {
        if (this.isConnected()) {
          this.sendHeartbeat()
        } else {
          this.clearHeartbeat()
        }
      }, 30000) // 每30秒发送一次心跳
    }
  }

  clearHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
    }
    if (this.heartbeatTimeout) {
      clearTimeout(this.heartbeatTimeout)
      this.heartbeatTimeout = null
    }
  }

  handleReconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.error('达到最大重连次数')
      this.connectionError = true
      return
    }

    this.reconnectAttempts++
    console.log(`尝试重新连接... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
    
    setTimeout(() => {
      if (!this.connectionError) {
        this.connect()
      }
    }, this.reconnectTimeout * this.reconnectAttempts)
  }

  isConnected() {
    return this.ws && this.ws.readyState === WebSocket.OPEN && !this.connectionError
  }

  subscribe(topic, callback) {
    if (!topic || typeof callback !== 'function') {
      console.error('订阅参数无效')
      return false
    }

    this.subscriptions.set(topic, callback)
    
    // 如果已连接，发送订阅消息
    if (this.isConnected()) {
      this.ws.send(JSON.stringify({
        type: 'subscribe',
        topic: topic
      }))
      return true
    }
    return false
  }

  unsubscribe(topic) {
    if (!topic) {
      console.error('取消订阅参数无效')
      return false
    }

    this.subscriptions.delete(topic)
    
    // 如果已连接，发送取消订阅消息
    if (this.isConnected()) {
      this.ws.send(JSON.stringify({
        type: 'unsubscribe',
        topic: topic
      }))
      return true
    }
    return false
  }

  sendMessage(topic, payload) {
    if (!topic) {
      console.error('发送消息参数无效')
      return false
    }

    if (this.isConnected()) {
      this.ws.send(JSON.stringify({
        type: 'message',
        topic: topic,
        payload: payload
      }))
      return true
    }
    return false
  }

  sendHeartbeat() {
    if (this.isConnected()) {
      this.ws.send(JSON.stringify({ type: 'ping' }))
      
      this.heartbeatTimeout = setTimeout(() => {
        console.warn('心跳超时 - 重新连接...')
        if (this.ws) {
          this.ws.close()
        }
      }, 5000) // 5秒超时
    }
  }
}

// 创建单例实例
const wsClient = new WebSocketClient()

// 导出方法
export default wsClient 